package fun.xiefeihong.video.list.service.impl

import fun.xiefeihong.video.list.conf.FileConf
import fun.xiefeihong.video.list.entity.FolderInfo
import fun.xiefeihong.video.list.entity.VideoInfo
import fun.xiefeihong.video.list.service.VideoFileService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId

@Service
class VideoFileServiceImpl implements VideoFileService{

    static final Logger log = LoggerFactory.getLogger(VideoFileServiceImpl.class)

    @Autowired
    FileConf fileConf

    @Override
    List<FolderInfo> getFolderInfos() {
        def folder = new File(fileConf.root)
        def folderInfos = []
        if(folder.isDirectory()){
            folder.listFiles().sort().each { file ->
                def instant = Instant.ofEpochMilli(file.lastModified())
                def localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                def folderInfo = new FolderInfo(file.name, localDateTime)
                folderInfos << folderInfo
            }
        }
        folderInfos
    }

    @Override
    List<VideoInfo> getVideoInfos(String folderPath) {
        def folder = new File("${fileConf.root}${folderPath}")
        def videoInfos = []
        if(folder.isDirectory()){
            folder.listFiles().sort().each { file ->
                def instant = Instant.ofEpochMilli(file.lastModified())
                def localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                def videoInfo = new VideoInfo(file.name, localDateTime, file.length() / 1024 / 1024 as int)
                videoInfos << videoInfo
            }
        }
        videoInfos
    }

}
